import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _extends from "@babel/runtime/helpers/esm/extends";
import { createVNode as _createVNode } from "vue";

var __rest = this && this.__rest || function (s, e) {
  var t = {};

  for (var p in s) {
    if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
  }

  if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
    if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
  }
  return t;
};

import { useInjectTreeContext } from './contextTypes';
import { getDataAndAria } from './util';
import Indent from './Indent';
import { convertNodePropsToEventData } from './utils/treeUtil';
import { computed, defineComponent, getCurrentInstance, onMounted, onUpdated, reactive, ref } from 'vue';
import { treeNodeProps } from './props';
import classNames from '../_util/classNames';
import { warning } from '../vc-util/warning';
import pick from 'lodash-es/pick';
var ICON_OPEN = 'open';
var ICON_CLOSE = 'close';
var defaultTitle = '---';
export default defineComponent({
  name: 'TreeNode',
  inheritAttrs: false,
  props: treeNodeProps,
  isTreeNode: 1,
  slots: ['title', 'icon', 'switcherIcon'],
  setup: function setup(props, _ref) {
    var attrs = _ref.attrs,
        slots = _ref.slots,
        expose = _ref.expose;
    warning(!('slots' in props.data), "treeData slots is deprecated, please use ".concat(Object.keys(props.data.slots || {}).map(function (key) {
      return '`v-slot:' + key + '` ';
    }), "instead"));
    var dragNodeHighlight = ref(false);
    var context = useInjectTreeContext();
    var selectHandle = ref();
    var hasChildren = computed(function () {
      var eventKey = props.eventKey;
      var keyEntities = context.value.keyEntities;

      var _ref2 = keyEntities[eventKey] || {},
          children = _ref2.children;

      return !!(children || []).length;
    });
    var isLeaf = computed(function () {
      var isLeaf = props.isLeaf,
          loaded = props.loaded;
      var loadData = context.value.loadData;
      var has = hasChildren.value;

      if (isLeaf === false) {
        return false;
      }

      return isLeaf || !loadData && !has || loadData && loaded && !has;
    });
    var nodeState = computed(function () {
      var expanded = props.expanded;

      if (isLeaf.value) {
        return null;
      }

      return expanded ? ICON_OPEN : ICON_CLOSE;
    });
    var isDisabled = computed(function () {
      var disabled = props.disabled;
      var treeDisabled = context.value.disabled;
      return !!(treeDisabled || disabled);
    });
    var isCheckable = computed(function () {
      var checkable = props.checkable;
      var treeCheckable = context.value.checkable; // Return false if tree or treeNode is not checkable

      if (!treeCheckable || checkable === false) return false;
      return treeCheckable;
    });
    var isSelectable = computed(function () {
      var selectable = props.selectable;
      var treeSelectable = context.value.selectable; // Ignore when selectable is undefined or null

      if (typeof selectable === 'boolean') {
        return selectable;
      }

      return treeSelectable;
    });
    var renderArgsData = computed(function () {
      return _extends(_extends(_extends({}, pick(props, ['active', 'checkable', 'checked', 'disableCheckbox', 'disabled', 'expanded', 'isLeaf', 'loading', 'selectable', 'selected', 'halfChecked'])), props.data), {
        dataRef: props.data,
        data: props.data,
        isLeaf: isLeaf.value
      });
    });
    var instance = getCurrentInstance();
    var eventData = computed(function () {
      var eventKey = props.eventKey;
      var keyEntities = context.value.keyEntities;

      var _ref3 = keyEntities[eventKey] || {},
          parent = _ref3.parent;

      return _extends(_extends({}, convertNodePropsToEventData(props)), {
        parent: parent
      });
    });
    var dragNodeEvent = reactive({
      eventData: eventData,
      eventKey: computed(function () {
        return props.eventKey;
      }),
      selectHandle: selectHandle,
      pos: computed(function () {
        return props.pos;
      }),
      key: instance.vnode.key
    });
    expose(dragNodeEvent);

    var onSelectorDoubleClick = function onSelectorDoubleClick(e) {
      var onNodeDoubleClick = context.value.onNodeDoubleClick;
      onNodeDoubleClick(e, eventData.value);
    };

    var onSelect = function onSelect(e) {
      if (isDisabled.value) return;
      var onNodeSelect = context.value.onNodeSelect;
      e.preventDefault();
      onNodeSelect(e, eventData.value);
    };

    var onCheck = function onCheck(e) {
      if (isDisabled.value) return;
      var disableCheckbox = props.disableCheckbox,
          checked = props.checked;
      var onNodeCheck = context.value.onNodeCheck;
      if (!isCheckable.value || disableCheckbox) return;
      e.preventDefault();
      var targetChecked = !checked;
      onNodeCheck(e, eventData.value, targetChecked);
    };

    var onSelectorClick = function onSelectorClick(e) {
      // Click trigger before select/check operation
      var onNodeClick = context.value.onNodeClick;
      onNodeClick(e, eventData.value);

      if (isSelectable.value) {
        onSelect(e);
      } else {
        onCheck(e);
      }
    };

    var onMouseEnter = function onMouseEnter(e) {
      var onNodeMouseEnter = context.value.onNodeMouseEnter;
      onNodeMouseEnter(e, eventData.value);
    };

    var onMouseLeave = function onMouseLeave(e) {
      var onNodeMouseLeave = context.value.onNodeMouseLeave;
      onNodeMouseLeave(e, eventData.value);
    };

    var onContextmenu = function onContextmenu(e) {
      var onNodeContextMenu = context.value.onNodeContextMenu;
      onNodeContextMenu(e, eventData.value);
    };

    var onDragStart = function onDragStart(e) {
      var onNodeDragStart = context.value.onNodeDragStart;
      e.stopPropagation();
      dragNodeHighlight.value = true;
      onNodeDragStart(e, dragNodeEvent);

      try {
        // ie throw error
        // firefox-need-it
        e.dataTransfer.setData('text/plain', '');
      } catch (error) {// empty
      }
    };

    var onDragEnter = function onDragEnter(e) {
      var onNodeDragEnter = context.value.onNodeDragEnter;
      e.preventDefault();
      e.stopPropagation();
      onNodeDragEnter(e, dragNodeEvent);
    };

    var onDragOver = function onDragOver(e) {
      var onNodeDragOver = context.value.onNodeDragOver;
      e.preventDefault();
      e.stopPropagation();
      onNodeDragOver(e, dragNodeEvent);
    };

    var onDragLeave = function onDragLeave(e) {
      var onNodeDragLeave = context.value.onNodeDragLeave;
      e.stopPropagation();
      onNodeDragLeave(e, dragNodeEvent);
    };

    var onDragEnd = function onDragEnd(e) {
      var onNodeDragEnd = context.value.onNodeDragEnd;
      e.stopPropagation();
      dragNodeHighlight.value = false;
      onNodeDragEnd(e, dragNodeEvent);
    };

    var onDrop = function onDrop(e) {
      var onNodeDrop = context.value.onNodeDrop;
      e.preventDefault();
      e.stopPropagation();
      dragNodeHighlight.value = false;
      onNodeDrop(e, dragNodeEvent);
    }; // Disabled item still can be switch


    var onExpand = function onExpand(e) {
      var onNodeExpand = context.value.onNodeExpand;
      if (props.loading) return;
      onNodeExpand(e, eventData.value);
    };

    var renderSwitcherIconDom = function renderSwitcherIconDom() {
      var _a, _b, _c;

      var _props$switcherIcon = props.switcherIcon,
          switcherIconFromProps = _props$switcherIcon === void 0 ? slots.switcherIcon || ((_a = context.value.slots) === null || _a === void 0 ? void 0 : _a[(_c = (_b = props.data) === null || _b === void 0 ? void 0 : _b.slots) === null || _c === void 0 ? void 0 : _c.switcherIcon]) : _props$switcherIcon;
      var switcherIconFromCtx = context.value.switcherIcon;
      var switcherIcon = switcherIconFromProps || switcherIconFromCtx; // if switcherIconDom is null, no render switcher span

      if (typeof switcherIcon === 'function') {
        return switcherIcon(renderArgsData.value);
      }

      return switcherIcon;
    }; // Load data to avoid default expanded tree without data


    var syncLoadData = function syncLoadData() {
      var expanded = props.expanded,
          loading = props.loading,
          loaded = props.loaded;
      var _context$value = context.value,
          loadData = _context$value.loadData,
          onNodeLoad = _context$value.onNodeLoad;

      if (loading) {
        return;
      } // read from state to avoid loadData at same time


      if (loadData && expanded && !isLeaf.value) {
        // We needn't reload data when has children in sync logic
        // It's only needed in node expanded
        if (!hasChildren.value && !loaded) {
          onNodeLoad(eventData.value);
        }
      }
    };

    onMounted(function () {
      syncLoadData();
    });
    onUpdated(function () {
      // https://github.com/vueComponent/ant-design-vue/issues/4835
      syncLoadData();
    }); // Switcher

    var renderSwitcher = function renderSwitcher() {
      var expanded = props.expanded;
      var prefixCls = context.value.prefixCls; // if switcherIconDom is null, no render switcher span

      var switcherIconDom = renderSwitcherIconDom();

      if (isLeaf.value) {
        return switcherIconDom !== false ? _createVNode("span", {
          "class": classNames("".concat(prefixCls, "-switcher"), "".concat(prefixCls, "-switcher-noop"))
        }, [switcherIconDom]) : null;
      }

      var switcherCls = classNames("".concat(prefixCls, "-switcher"), "".concat(prefixCls, "-switcher_").concat(expanded ? ICON_OPEN : ICON_CLOSE));
      return switcherIconDom !== false ? _createVNode("span", {
        "onClick": onExpand,
        "class": switcherCls
      }, [switcherIconDom]) : null;
    }; // Checkbox


    var renderCheckbox = function renderCheckbox() {
      var _a, _b;

      var checked = props.checked,
          halfChecked = props.halfChecked,
          disableCheckbox = props.disableCheckbox;
      var prefixCls = context.value.prefixCls;
      var disabled = isDisabled.value;
      var checkable = isCheckable.value;
      if (!checkable) return null;
      return _createVNode("span", {
        "class": classNames("".concat(prefixCls, "-checkbox"), checked && "".concat(prefixCls, "-checkbox-checked"), !checked && halfChecked && "".concat(prefixCls, "-checkbox-indeterminate"), (disabled || disableCheckbox) && "".concat(prefixCls, "-checkbox-disabled")),
        "onClick": onCheck
      }, [(_b = (_a = context.value).customCheckable) === null || _b === void 0 ? void 0 : _b.call(_a)]);
    };

    var renderIcon = function renderIcon() {
      var loading = props.loading;
      var prefixCls = context.value.prefixCls;
      return _createVNode("span", {
        "class": classNames("".concat(prefixCls, "-iconEle"), "".concat(prefixCls, "-icon__").concat(nodeState.value || 'docu'), loading && "".concat(prefixCls, "-icon_loading"))
      }, null);
    };

    var renderDropIndicator = function renderDropIndicator() {
      var disabled = props.disabled,
          eventKey = props.eventKey;
      var _context$value2 = context.value,
          draggable = _context$value2.draggable,
          dropLevelOffset = _context$value2.dropLevelOffset,
          dropPosition = _context$value2.dropPosition,
          prefixCls = _context$value2.prefixCls,
          indent = _context$value2.indent,
          dropIndicatorRender = _context$value2.dropIndicatorRender,
          dragOverNodeKey = _context$value2.dragOverNodeKey,
          direction = _context$value2.direction;
      var mergedDraggable = draggable !== false; // allowDrop is calculated in Tree.tsx, there is no need for calc it here

      var showIndicator = !disabled && mergedDraggable && dragOverNodeKey === eventKey;
      return showIndicator ? dropIndicatorRender({
        dropPosition: dropPosition,
        dropLevelOffset: dropLevelOffset,
        indent: indent,
        prefixCls: prefixCls,
        direction: direction
      }) : null;
    }; // Icon + Title


    var renderSelector = function renderSelector() {
      var _a, _b, _c, _d, _e, _f;

      var selected = props.selected,
          _props$icon = props.icon,
          icon = _props$icon === void 0 ? slots.icon : _props$icon,
          loading = props.loading,
          data = props.data;
      var title = slots.title || ((_a = context.value.slots) === null || _a === void 0 ? void 0 : _a[(_c = (_b = props.data) === null || _b === void 0 ? void 0 : _b.slots) === null || _c === void 0 ? void 0 : _c.title]) || ((_d = context.value.slots) === null || _d === void 0 ? void 0 : _d.title) || props.title;
      var _context$value3 = context.value,
          prefixCls = _context$value3.prefixCls,
          showIcon = _context$value3.showIcon,
          treeIcon = _context$value3.icon,
          draggable = _context$value3.draggable,
          loadData = _context$value3.loadData;
      var disabled = isDisabled.value;
      var mergedDraggable = typeof draggable === 'function' ? draggable(data) : draggable;
      var wrapClass = "".concat(prefixCls, "-node-content-wrapper"); // Icon - Still show loading icon when loading without showIcon

      var $icon;

      if (showIcon) {
        var currentIcon = icon || ((_e = context.value.slots) === null || _e === void 0 ? void 0 : _e[(_f = data === null || data === void 0 ? void 0 : data.slots) === null || _f === void 0 ? void 0 : _f.icon]) || treeIcon;
        $icon = currentIcon ? _createVNode("span", {
          "class": classNames("".concat(prefixCls, "-iconEle"), "".concat(prefixCls, "-icon__customize"))
        }, [typeof currentIcon === 'function' ? currentIcon(renderArgsData.value) : currentIcon]) : renderIcon();
      } else if (loadData && loading) {
        $icon = renderIcon();
      } // Title


      var titleNode;

      if (typeof title === 'function') {
        titleNode = title(renderArgsData.value); // } else if (contextSlots.titleRender) {
        //   titleNode = contextSlots.titleRender(renderArgsData.value);
      } else {
        titleNode = title;
      }

      titleNode = titleNode === undefined ? defaultTitle : titleNode;

      var $title = _createVNode("span", {
        "class": "".concat(prefixCls, "-title")
      }, [titleNode]);

      return _createVNode("span", {
        "ref": selectHandle,
        "title": typeof title === 'string' ? title : '',
        "class": classNames("".concat(wrapClass), "".concat(wrapClass, "-").concat(nodeState.value || 'normal'), !disabled && (selected || dragNodeHighlight.value) && "".concat(prefixCls, "-node-selected"), !disabled && mergedDraggable && 'draggable'),
        "draggable": !disabled && mergedDraggable || undefined,
        "aria-grabbed": !disabled && mergedDraggable || undefined,
        "onMouseenter": onMouseEnter,
        "onMouseleave": onMouseLeave,
        "onContextmenu": onContextmenu,
        "onClick": onSelectorClick,
        "onDblclick": onSelectorDoubleClick,
        "onDragstart": mergedDraggable ? onDragStart : undefined
      }, [$icon, $title, renderDropIndicator()]);
    };

    return function () {
      var _classNames;

      var _a = _extends(_extends({}, props), attrs),
          eventKey = _a.eventKey,
          dragOver = _a.dragOver,
          dragOverGapTop = _a.dragOverGapTop,
          dragOverGapBottom = _a.dragOverGapBottom,
          isLeaf = _a.isLeaf,
          isStart = _a.isStart,
          isEnd = _a.isEnd,
          expanded = _a.expanded,
          selected = _a.selected,
          checked = _a.checked,
          halfChecked = _a.halfChecked,
          loading = _a.loading,
          domRef = _a.domRef,
          active = _a.active,
          data = _a.data,
          onMousemove = _a.onMousemove,
          otherProps = __rest(_a, ["eventKey", "dragOver", "dragOverGapTop", "dragOverGapBottom", "isLeaf", "isStart", "isEnd", "expanded", "selected", "checked", "halfChecked", "loading", "domRef", "active", "data", "onMousemove"]);

      var _context$value4 = context.value,
          prefixCls = _context$value4.prefixCls,
          filterTreeNode = _context$value4.filterTreeNode,
          draggable = _context$value4.draggable,
          keyEntities = _context$value4.keyEntities,
          dropContainerKey = _context$value4.dropContainerKey,
          dropTargetKey = _context$value4.dropTargetKey;
      var disabled = isDisabled.value;
      var dataOrAriaAttributeProps = getDataAndAria(otherProps);

      var _ref4 = keyEntities[eventKey] || {},
          level = _ref4.level;

      var isEndNode = isEnd[isEnd.length - 1];
      var mergedDraggable = typeof draggable === 'function' ? draggable(data) : draggable;
      return _createVNode("div", _objectSpread({
        "ref": domRef,
        "class": classNames(attrs.class, "".concat(prefixCls, "-treenode"), (_classNames = {}, _defineProperty(_classNames, "".concat(prefixCls, "-treenode-disabled"), disabled), _defineProperty(_classNames, "".concat(prefixCls, "-treenode-switcher-").concat(expanded ? 'open' : 'close'), !isLeaf), _defineProperty(_classNames, "".concat(prefixCls, "-treenode-checkbox-checked"), checked), _defineProperty(_classNames, "".concat(prefixCls, "-treenode-checkbox-indeterminate"), halfChecked), _defineProperty(_classNames, "".concat(prefixCls, "-treenode-selected"), selected), _defineProperty(_classNames, "".concat(prefixCls, "-treenode-loading"), loading), _defineProperty(_classNames, "".concat(prefixCls, "-treenode-active"), active), _defineProperty(_classNames, "".concat(prefixCls, "-treenode-leaf-last"), isEndNode), _defineProperty(_classNames, 'drop-target', dropTargetKey === eventKey), _defineProperty(_classNames, 'drop-container', dropContainerKey === eventKey), _defineProperty(_classNames, 'drag-over', !disabled && dragOver), _defineProperty(_classNames, 'drag-over-gap-top', !disabled && dragOverGapTop), _defineProperty(_classNames, 'drag-over-gap-bottom', !disabled && dragOverGapBottom), _defineProperty(_classNames, 'filter-node', filterTreeNode && filterTreeNode(eventData.value)), _classNames)),
        "style": attrs.style,
        "onDragenter": mergedDraggable ? onDragEnter : undefined,
        "onDragover": mergedDraggable ? onDragOver : undefined,
        "onDragleave": mergedDraggable ? onDragLeave : undefined,
        "onDrop": mergedDraggable ? onDrop : undefined,
        "onDragend": mergedDraggable ? onDragEnd : undefined,
        "onMousemove": onMousemove
      }, dataOrAriaAttributeProps), [_createVNode(Indent, {
        "prefixCls": prefixCls,
        "level": level,
        "isStart": isStart,
        "isEnd": isEnd
      }, null), renderSwitcher(), renderCheckbox(), renderSelector()]);
    };
  }
});